const fileService = require('../service/File.service')
const { updateAvatarByuserId } = require('../service/user.service')
const { APP_HOST, APP_PORT } = require('../app/config')
const userService = require('../service/user.service')

class FileController {
  async setUserAvatar(ctx, next) {
    const { id: userId } = ctx.user
    const { filename, mimetype, size } = ctx.request.file

    // 先判断用户头像是否已经存在
    const avatarExist = await fileService.checkAvatarExist(userId)

    // 不存在则创建用户头像
    if (!avatarExist) {
      // 保存头像图片信息到avatar表
      await fileService.careatAvatar(filename, mimetype, size, userId)
      const avatarUrl = `${APP_HOST}:${APP_PORT}/users/${userId}/avatar`
      // 更新user表，添加头像地址
      await userService.updateAvatarByuserId(avatarUrl, userId)
    } else {
      // 存在则更新avatar表
      await fileService.updateAvatar(filename, mimetype, size, userId)
    }
    ctx.body = '设置头像成功'
  }
  async savePictureInfo(ctx, next) {
    const { id: userId } = ctx.user
    const { momentId } = ctx.query
    const files = ctx.files
    for (const file of files) {
      const { filename, mimetype, size } = file
      await fileService.savePictureInfo(filename, mimetype, size, momentId, userId)
    }
    ctx.body = '上传图片成功'
  }
}

module.exports = new FileController()
